package com.nari.kmd_dataservice.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.nari.kmd_dataservice.constant.ConstantParameter;
import com.nari.kmd_dataservice.pojo.request.laRegister.LaRegisterRequest;
import org.json.JSONObject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @ClassName: JwtUtils
 * @Description: Jwt token
 * @Author: LZL
 * @Date: 2022/01/24 10:33
 * @Version 1.0.0
 */
public class JwtUtils {
    public static String getTokenUserId() {
        String token = getRequest().getHeader("token");// 从 http 请求头中取出 token
        String userId = JWT.decode(token).getAudience().get(0);
        return userId;
    }
    /**
      * 获取request
      *
      * @return
     */
    public static HttpServletRequest getRequest() {
     ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
             .getRequestAttributes();
     return requestAttributes == null ? null : requestAttributes.getRequest();
    }

    /**
     * 获取token
     */
    public static String getToken(LaRegisterRequest user){
        Date start = new Date();
        long currentTime = System.currentTimeMillis() + ConstantParameter.localTokenOutMinute * 60 * 1000;//有效时间
        Date end = new Date(currentTime);
        String token = "";
//        token = JWT.create().withAudience(user.getUserName()).withIssuedAt(start).withExpiresAt(end)
//                .sign(Algorithm.HMAC256(user.getPassword()));
//        token = JWT.create().withClaim("userName", user.getUserName()).withClaim("password", user.getPassword()).withExpiresAt(end)
//                .sign(Algorithm.HMAC256(ConstantParameter.tokenKey));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("u", user.getUserName());
        jsonObject.put("p", user.getPassword());
        String encrypt = SM4.encryptEcb(ConstantParameter.tokenParaSM4Key, jsonObject.toString());
        System.out.println("encrypt="+encrypt);
        token = JWT.create().withClaim("e", encrypt).withExpiresAt(end)
                .sign(Algorithm.HMAC256(ConstantParameter.tokenKey));
        return token;
    }
}
